package com.fansl.allround.common.core.validator;

import com.baidu.unbiz.fluentvalidator.ValidationError;
import com.baidu.unbiz.fluentvalidator.Validator;
import com.baidu.unbiz.fluentvalidator.ValidatorContext;
import com.baidu.unbiz.fluentvalidator.ValidatorHandler;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author fansl
 * @Description: 手机号验证
 * @date 2019/10/10 15:28
 */
public class MobileValidator extends ValidatorHandler<String> implements Validator<String> {
    private static String regex = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$";
    private static int mobileLength = 11;
    public MobileValidator() {

    }

    @Override
    public boolean validate(ValidatorContext context, String mobile) {
        if (mobile.length()!=mobileLength){
            context.addError(ValidationError.create(String.format("手机号码长度不正确！"))
                    .setErrorCode(-1)
                    .setInvalidValue(mobile));
            return false;
        }
        Pattern p  = Pattern.compile(regex);
        Matcher matcher = p.matcher(mobile);
        if (!matcher.matches()) {
            context.addError(ValidationError.create(String.format("手机号码不正确！"))
                    .setErrorCode(-1)
                    .setInvalidValue(mobile));
            return false;
        }
        return true;
    }
}
